package com.afonddream.awesome.asm;

import com.afonddream.awesome.log.GLog;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class CommentFactory {
    private static CommentFactory ourInstance = new CommentFactory();

    public static CommentFactory getInstance() {
        return ourInstance;
    }

    private Properties prop = new Properties();

    private CommentFactory() {
        this.initProp("src/main/resources/assembly/assembly_comment.properties");
    }

    private void initProp(String asmPropPath) {
        try (FileInputStream in = new FileInputStream(asmPropPath)) {
            this.prop.load(new InputStreamReader(in, "utf-8"));
        } catch (IOException e) {
            GLog.getLog().error("load {} fail!", asmPropPath, e);
        }
    }

    public List<String> addComment(FileInputStream in) {
        List<String> contents = new ArrayList<>();
        try (
                FileReader reader = new FileReader(in.getFD());
                BufferedReader br = new BufferedReader(reader)
        ) {
            while (br.ready()) {
                String l = br.readLine();
                contents.add(convert(l));
            }

        } catch (IOException e) {
            GLog.getLog().error("add commit fail");
            return new ArrayList<>();
        }

        return contents;
    }

    private String convert(String line) {
        if (!StringUtils.isEmpty(line)
                && line.startsWith(" ")
                && line.contains("\t")) {
            String[] arr = line.split("\t");
            if (arr.length >= 3) {
                String temp = arr[2].trim();
                String key;
                if (temp.contains(" ")) {
                    key = temp.substring(0, temp.indexOf(' '));
                } else {
                    key = temp;
                }

                String m = this.prop.getProperty(key);
                if (!StringUtils.isEmpty(m)) {
                    return line + "\t#" + m;
                }
            }
        }
        return line;
    }
}
